﻿using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using JWT;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ABenNet.Jwt.HS256;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using System.Windows.Forms.VisualStyles;

namespace AES小工具
{
    public partial class FrmJwt : Form
    {
        public FrmJwt()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 時間戳转时间
        /// </summary>
        /// <param name="sec"></param>
        /// <returns></returns>
        private DateTime getDateTime(int sec) {
            System.DateTime startTime = System.TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));//获取时间戳
            System.DateTime dt = startTime.AddSeconds(sec);
            //dt = dt.AddMonths(4);
            return dt;
        }


        private string[] splitString(string str,int minLen) { 
            
            if(str.Length % minLen > 0) {
                return null;
            }
            string[] strs = new string[str.Length / minLen];
            for(int i = 0;i < strs.Length; i++)
            {
                strs[i] = str.Substring(i * minLen, minLen);
            }
            return strs;
        }

        private byte[] hexString2Bytes(string hexString) { 
            string[] strs = splitString(hexString, 2);
            if (strs == null) 
                return null;
            byte[] bytes = new byte[strs.Length];
            for(int i = 0; i < strs.Length; i++)
            {
                bytes[i] = Convert.ToByte(strs[i], 16);
            }
            return bytes;
        }

        readonly string tailStr = "\r\n";
        private void btnDecode_Click(object sender, EventArgs e)
        {
            string encryptedText = tbToken.Text.Trim();
            string signature = "";
            string token = tbToken.Text.Trim();

            try {
                if (cbAesCbc.Checked)
                {
                    string pass = calcPassword(tbAesRandomStr.Text.Trim());
                    token = AESHelper.AESDecrypt2CBCPkcs7ToString(hexString2Bytes(encryptedText), pass, pass);
                    Console.WriteLine(token);
                }

                //通过token明文获取用户信息及有效期
                JwtSecurityToken jst = JwtTokenManager.parse(token, signature);
                int count = jst.Payload.Count;
                var keys = jst.Payload.Keys.ToList();
                tbJson.Text = "";
                foreach (string key in keys)
                {
                    if (key.Equals("role") || key.Equals("sub") || key.Equals("jti"))
                        continue;
                    tbJson.Text += key + ":" + jst.Payload[key] + tailStr;
                }

                if (jst.Payload.ContainsKey("exp"))
                {
                    DateTime dt = getDateTime(int.Parse(jst.Payload["exp"].ToString()));
                    string dateStr = dt.ToString("yyyy-MM-dd HH:mm:ss");
                    tbJson.Text += "有效期:" + dateStr + tailStr;
                }
            } catch {
                MessageBox.Show("解码异常，请确认输入是否正确!");
            }
        }

        private string calcPassword(string randomStr) {
            char[] chars = randomStr.ToUpper().ToCharArray();

            int first = chars[0];
            int last = chars[chars.Length - 1];

            int total = first + last;
            string pass = "";
            for (int i = 2; i <= 5; i++)
            {
                int ind = total / i;
                ind = ind % 26;
                Console.WriteLine("index:" + ind);
                pass += randomStr.Substring(ind, 4);
            }
            return pass;
        }

        private void btnGetAesPassword_Click(object sender, EventArgs e)
        {
            string randomStr = tbAesRandomStr.Text.Trim();
            if (string.IsNullOrEmpty(randomStr)) {
                MessageBox.Show("密码字符串不能为空!");
                return;
            }
            if(randomStr.Length != 32) {
                MessageBox.Show("密码字符串长度必须为32字符");
                return;
            }
            /*char[] chars = randomStr.ToUpper().ToCharArray();

            int first = chars[0];
            int last = chars[chars.Length - 1];

            int total = first + last;
            string pass = "";
            for(int i = 2; i <= 5;i++)
            {
                int ind = total / i;
                ind = ind % 26;
                Console.WriteLine("index:" +  ind);
                pass += randomStr.Substring(ind, 4);
            }*/

            tbToken.Text = calcPassword(randomStr);

        }

        private void cbAesCbc_CheckedChanged(object sender, EventArgs e)
        {
            tbAesRandomStr.Enabled = cbAesCbc.Checked;
        }

        private void FrmJwt_Load(object sender, EventArgs e)
        {
            tbAesRandomStr.Enabled = cbAesCbc.Checked;
        }
    }
}
